<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">
        <h2>二手车交易平台</h2>
        <p>欢迎回来，请登录您的账号</p>
      </div>
      
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名/手机号"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            placeholder="请输入密码" 
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <div class="login-options">
          <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
          <el-link type="primary" :underline="false" @click="forgetPassword">忘记密码?</el-link>
        </div>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="login-button" 
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        
        <div class="register-link">
          还没有账号? <el-link type="primary" @click="goToRegister">立即注册</el-link>
        </div>
        
        <div class="other-login">
          <div class="divider">
            <span>其他登录方式</span>
          </div>
          <div class="social-icons">
            <el-button circle><i class="fab fa-weixin"></i></el-button>
            <el-button circle><i class="fab fa-qq"></i></el-button>
            <el-button circle><i class="fas fa-mobile-alt"></i></el-button>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '@/api/auth'
import { setToken, setUserInfo } from '@/utils/auth'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符之间', trigger: 'blur' }
  ]
}

// 登录处理函数
const handleLogin = () => {
  loginFormRef.value.validate(valid => {
    if (!valid) return
    
    loading.value = true
    
    // 调用登录API
    login(loginForm.username, loginForm.password)
      .then(res => {
        if (!res.success) {
          ElMessage.error(res.message || '登录失败')
          return Promise.reject(new Error(res.message || '登录失败'))
        }
        
        console.log('登录成功，后端返回数据:', res)
        
        // 保存token
        setToken(res.token)
        
        // 保存完整的用户信息
        const userInfo = {
          userId: res.userId,
          username: res.username,
          nickname: res.nickname,
          userType: res.userType,
          email: res.email,
          phone: res.phone,
          avatar: res.avatar,
          gender: res.gender,
          status: res.status,
          createTime: res.createTime,
          updateTime: res.updateTime,
          remark: res.remark
        }
        
        // 使用auth.js中的setUserInfo函数保存用户信息
        setUserInfo(userInfo)
        
        // 保存"记住我"设置
        if (loginForm.rememberMe) {
          localStorage.setItem('remember', JSON.stringify({
            username: loginForm.username,
            rememberMe: true
          }))
        } else {
          localStorage.removeItem('remember')
        }
        
        ElMessage.success('登录成功')
        
        // 获取重定向地址
        const redirect = new URLSearchParams(window.location.search).get('redirect')
        
        // 跳转到重定向地址或者首页
        router.push(redirect || '/')
      })
      .catch(error => {
        console.error('登录失败:', error)
        ElMessage.error(error.message || '登录失败，请检查用户名和密码')
      })
      .finally(() => {
        loading.value = false
      })
  })
}

// 忘记密码
const forgetPassword = () => {
  router.push('/forget-password')
}

// 跳转到注册页
const goToRegister = () => {
  router.push('/register')
}

// 检查是否有记住的登录信息
const checkRememberedLogin = () => {
  const remembered = localStorage.getItem('remember')
  if (remembered) {
    const { username, rememberMe } = JSON.parse(remembered)
    loginForm.username = username
    loginForm.rememberMe = rememberMe
  }
}

// 页面加载时执行
checkRememberedLogin()
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: url('@/assets/images/login-bg.jpg') no-repeat center center;
  background-size: cover;
  
  .login-box {
    width: 420px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 10px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  }
  
  .login-title {
    text-align: center;
    margin-bottom: 30px;
    
    h2 {
      font-size: 24px;
      color: #333;
      margin-bottom: 10px;
    }
    
    p {
      font-size: 14px;
      color: #666;
      margin: 0;
    }
  }
  
  .login-form {
    .el-input {
      margin-bottom: 5px;
      height: 50px;
      
      :deep(.el-input__wrapper) {
        padding: 0 15px;
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        
        &.is-focus {
          box-shadow: 0 0 0 1px #409eff inset;
        }
      }
    }
  }
  
  .login-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .login-button {
    width: 100%;
    height: 45px;
    border-radius: 4px;
    font-size: 16px;
  }
  
  .register-link {
    text-align: center;
    margin: 15px 0;
    font-size: 14px;
    color: #666;
  }
  
  .other-login {
    margin-top: 30px;
    
    .divider {
      display: flex;
      align-items: center;
      color: #999;
      font-size: 12px;
      margin-bottom: 20px;
      
      &:before,
      &:after {
        content: '';
        flex: 1;
        border-top: 1px solid #eee;
      }
      
      span {
        padding: 0 15px;
      }
    }
    
    .social-icons {
      display: flex;
      justify-content: center;
      gap: 20px;
      
      .el-button {
        font-size: 18px;
        color: #666;
      }
    }
  }
}

// 移动端适配
@media (max-width: 576px) {
  .login-container {
    .login-box {
      width: 90%;
      padding: 30px 20px;
    }
  }
}
</style> 